package com.qf.fmall.index.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.index.entity.Product;
import com.qf.fmall.index.entity.ProductImg;
import com.qf.fmall.index.mapper.ProductDao;
import com.qf.fmall.index.mapper.ProductImgDao;
import com.qf.fmall.index.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2024-01-17
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements IProductService {

    @Autowired
    private ProductImgDao productImgDao;

    @Override
    public List<Product> listRecommends() {

        //1. 按照商品的上架时间倒叙取前三个商品
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 3");
        List<Product> products = list(queryWrapper);

        //2. 把products中的商品对象的 imgs属性赋值
        addImgs(products);

        return products;
    }

    /**
     * 能否只查询一次数据库？
     * @param products
     */
    private void addImgs(List<Product> products) {
        //1. 遍历products，查询每个商品对应的图片信息
        for (Product product : products) {
            Integer productId = product.getProductId();
            List<ProductImg> imgs = productImgDao.selectList(new QueryWrapper<ProductImg>().eq("product_id", productId));
            product.setImgs(imgs);
        }
    }
}
